package cn.bdqn.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;

import cn.bdqn.pojo.Role;
import cn.bdqn.pojo.User;
import cn.bdqn.service.RoleService;
import cn.bdqn.service.UserService;
import cn.bdqn.util.PageBean;

@Controller()
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	
	
	
	@RequestMapping("/logout")
	public String out(HttpSession session){
//		session.removeAttribute("user");
		session.invalidate();
		return "redirect:/index.html";
	}
	
	@RequestMapping("/showPage")
	public String showAll(@RequestParam(value="queryname",required=false)String userName,
			@RequestParam(value="queryUserRole",required=false)Integer roleId,
			@RequestParam(value="pageNo",required=false,defaultValue="1")Integer pageNo,
			Model model){
		int pageSize=6;
//		if(userName!=null){
//			try {
//				userName=new String(userName.getBytes("iso-8859-1"),"UTF-8");
//				model.addAttribute("queryUserName",userName);
//			} catch (UnsupportedEncodingException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
		PageBean<User> pBean=userService.findByPage(pageNo, pageSize, userName, roleId);
		List<Role> rlist=roleService.findAll();
		model.addAttribute("pageBean",pBean);
		model.addAttribute("roleList",rlist);
		model.addAttribute("queryUserName",userName);
		model.addAttribute("queryUserRole",roleId);
		return "userlist";		
	}
	
		@RequestMapping("/useradd.html")
		public String  showUseradd(Model model){
			return "useradd";
		}
		
		@RequestMapping("/useradd.do")
		public String useradd(User user,HttpSession session,@RequestParam("a_idPicPath")MultipartFile idPicPath,@RequestParam("a_workPicPath")MultipartFile workPicPath){
			User u=(User)session.getAttribute("userlogin");
			String filePath=session.getServletContext().getRealPath("statics"+File.separator+"images");
			String idpicName=System.currentTimeMillis()+""+Math.round((Math.random()*10000))+idPicPath.getOriginalFilename();
			String workpicName=System.currentTimeMillis()+""+Math.round((Math.random()*10000))+workPicPath.getOriginalFilename();
			File idfileTo=new File(filePath, idpicName);
			File workfileTo=new File(filePath,workpicName);
			try {
				idPicPath.transferTo(idfileTo);
				workPicPath.transferTo(workfileTo);
				user.setCreatedBy(u.getId());
				user.setCreationDate(new Date());
				user.setIdPicPath(idpicName);
				user.setWorkPicPath(workpicName);
			}catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return "error";
			}
			if(userService.addUser(user)){
				return "success";
			}else{
				return "useradd";
			}
		}
		
		@ResponseBody
		@RequestMapping("/view/{uid}")
		public Object view(@PathVariable Integer uid){
			User user=userService.findById(uid);
			return user;
		}
		
		@ResponseBody
		@RequestMapping("/delete/{uid}")
		public Object delete(@PathVariable Integer uid){
			User user=userService.findById(uid);
			Map<String, Object> map=new HashMap<String, Object>();
			if(user==null){
				map.put("delResult", "notexist");
			}else{
				int result=userService.deleteById(uid);
				if(result>0){
					map.put("delResult", "true");
				}else{
					map.put("delResult", "false");

				}
			}
			return map;
		}
			
		@RequestMapping("/modify/{uid}")
		public String modify(@PathVariable Integer uid,Model model){
			User user=userService.findById(uid);
			model.addAttribute("user",user);
			return "usermodify";
		}
		
		@RequestMapping("/domodify")
		public String domodify(User user,HttpSession session){
			User u=(User)session.getAttribute("userlogin");
			user.setModifyBy(u.getId());
			user.setModifyDate(new Date());
			if(userService.updateByUser(user)){
				return "success";
			}else{
				return "usermodify";
			}
		}
		
		//produces={"application/json;charset=UTF-8"}
		@ResponseBody
		@RequestMapping(value="/getrolelist")
		public Object getrolelist(){
			List<Role> rlist=roleService.findAll();
			return rlist;
		}
		
		@ResponseBody
		@RequestMapping(value="/checkUserCode")
		public Object checkUserCode(@RequestParam("userCode")String userCode){
			boolean isOk=userService.checkUserCode(userCode);
			Map<String, Object> map=new HashMap<String, Object>();
			if(isOk){
				map.put("userCode","exist");
			}else{
				map.put("userCode","noexist");
			}
			return map;
		}
		
		@RequestMapping("pwdmodify")
		public String pwdmodify(){
			return "pwdmodify";
		}
		
		@ResponseBody
		@RequestMapping("/checkpwd")
		public Object checkpwd(@RequestParam(value="oldpassword",required=false)String pwd,HttpSession session,Model model){
			User user=(User) session.getAttribute("userlogin");
			Map<String, Object> map=new HashMap<String, Object>();
			
			if(user!=null&&pwd!=null&&pwd!=""){
				boolean isOk=pwd.equals(user.getUserPassword())?true:false;
				if(isOk){
					map.put("result","true");
				}else{
					map.put("result","false");
				}
			}else if(user==null){
				map.put("result","sessionerror");
			}else{
				map.put("result","error");
			}
			return map;
		}
		
		@RequestMapping("doPwdmodify")
		public String doPwdmodify(HttpSession session,@RequestParam("newpassword")String newpassword){
			User user=(User) session.getAttribute("userlogin");
			user.setUserPassword(newpassword);
			userService.updateByUser(user);
			return "redirect:/user/logout";
		}
}
